from fastapi import APIRouter, HTTPException, Query, Depends
from typing import List, Optional
from datetime import datetime
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.models.task import Task
from app.models.stream import Stream

router = APIRouter()

@router.get("/list")
async def get_recordings(
    page: int = Query(1, ge=1, description="页码"),
    limit: int = Query(20, ge=1, le=100, description="每页数量"),
    name: Optional[str] = Query(None, description="录制名称模糊搜索"),
    status: Optional[str] = Query(None, description="状态筛选"),
    stream_id: Optional[int] = Query(None, description="流ID筛选"),
    db: Session = Depends(get_db)
):
    """获取录制列表"""
    query = db.query(Task).filter(Task.task_type == "record")
    
    # 筛选条件
    if name:
        query = query.join(Stream).filter(Stream.name.contains(name))
    if status:
        query = query.filter(Task.status == status)
    if stream_id:
        query = query.filter(Task.stream_id == stream_id)
    
    # 分页
    total = query.count()
    tasks = query.offset((page - 1) * limit).limit(limit).all()
    
    recordings = []
    for task in tasks:
        stream = db.query(Stream).filter(Stream.id == task.stream_id).first()
        if stream:
            recordings.append({
                "id": task.id,
                "name": stream.name,
                "url": stream.url,
                "status": task.status,
                "start_time": task.start_time.isoformat() if task.start_time else None,
                "end_time": task.end_time.isoformat() if task.end_time else None,
                "recording_url": f"/recordings/{stream.name}/index.m3u8",
                "file_count": 0,
                "size": 0,
                "codec": "H.264",
                "bitrate": 2500,
                "resolution": "1920x1080"
            })
    
    return {
        "code": 200,
        "data": {
            "items": recordings,
            "total": total
        },
        "message": "success"
    }

@router.post("/{recording_id}/start")
async def start_recording(recording_id: int):
    """启动录制 - 兼容前端接口"""
    return {"success": True, "message": "录制已启动"}

@router.post("/{recording_id}/stop")
async def stop_recording(recording_id: int):
    """停止录制 - 兼容前端接口"""
    return {"success": True, "message": "录制已停止"}